﻿using IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class BaseDAL<T>:IBaseDAL<T> where T : class
    {
        /// <summary>
        /// 注入上下文
        /// </summary>
        /// <param name="db">别名</param>
        public BaseDAL(MyDbContext db)
        {
            Db = db;
        }
        /// <summary>
        /// 创建属性并赋值
        /// </summary>
        public MyDbContext Db { get; }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t">数据对象</param>
        /// <returns>返回受影响行数</returns>
       public async Task<int> AddAsync(T t)
        {
            await Db.Set<T>().AddAsync(t);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="list">数据对象集合</param>
        /// <returns>返回受影响行数</returns>
       public async Task<int> AddRangeAsync(List<T> list)
        {
            await Db.Set<T>().AddRangeAsync(list);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="t">数据对象</param>
        /// <returns>返回受影响行数</returns>
       public  async Task<int> DeleteAsync(T t)
        {
            Db.Set<T>().Remove(t);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="list">数据对象集合</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> DeleteRangeAsync(List<T> list)
        {
            Db.Set<T>().RemoveRange(list);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="t">数据对象</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> UpdateAsync(T t)
        {
            Db.Set<T>().Update(t);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="list">数据对象集合</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> UpdateRangeAsync(List<T> list)
        {
            Db.Set<T>().UpdateRange(list);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 延迟执行 解决查询
        /// </summary>
        /// <returns>返回 IQueryable<T> 对象</returns>
        public IQueryable<T> GetAllAsync()
        {
            return Db.Set<T>();
        }
    }
}
